'use strict'

var EventEmitter = require('events');
var util = require('util');

var PeerQueue = require('./peer-queue');
const {fork} = require('child_process');
const path = require('path');
const { formatTime } = require('./utils');


var BTClient = function(options) {
    EventEmitter.call(this);
    options = Object.assign({}, options);
    this.active = 0
    this.maxActive = 50
    this.timeout = 5000;
    this.maxConnections = options.maxConnections || 5000;
    this.peers = new PeerQueue(this.maxConnections);
    this.child = fork(path.resolve(__dirname, './child'), {windowsHide: true, serialization: 'advanced'});
    this.child.on('message', args => {
       if(args.type === 'complete') {
           this.emit('complete', args.metadata, args.infoHash, args.rinfo);
       } else if(args.type === 'next') {
            this.active--
           this.next();
       }
    });
};

util.inherits(BTClient, EventEmitter);

BTClient.prototype.next = function() {
    if(this.active < this.maxActive) {
        var req = this.peers.shift();
        if(req) {
            this.download(req.rinfo, req.infohash);
        }
    }
}

BTClient.prototype.download = function(rinfo, infohash) {
    this.active++
    this.child.send({
        rinfo,
        infohash,
        timeout: this.timeout
    })
};

BTClient.prototype.add = function(rinfo, infohash) {
    this.peers.push({infohash: infohash, rinfo: rinfo});
    this.next()
};

module.exports = BTClient;